package com.controller;

import com.alibaba.fastjson.JSON;
import com.pojo.User;
import com.service.UserService;
import com.utils.Constants;
import com.utils.PageSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping(value="/user/view/{uid}")
    public String viewUser(@PathVariable Integer uid, Model model) {
        User user=userService.getUserByUid(uid);
        model.addAttribute("user", user);
        return "/user/view";
    }

    @GetMapping(value="/user/update.html/{uid}")
    public String updateUser(@PathVariable Integer uid, Model model) {
        System.out.println("updateUser ID:"+uid);
        // 获取待修改用户信息
        User user=userService.getUserByUid(uid);
        model.addAttribute("user", user);
        return "/user/modify";
    }

    @PostMapping(value="/user/update.html")
    public String doUpdateUser(@Valid User user, BindingResult bindingResult,
                               HttpSession session) {
        System.out.println("doUpdateUser");
        if(bindingResult.hasErrors()) {
            return "/user/modify";
        }

        boolean val=userService.updateUserByUid(user);
        if(val) {
            System.out.println("success");
            // 成功：转跳用户列表页面
            return "redirect:/user/list.html";
        }
        System.out.println("failure");
        // 失败：返回添加用户页面
        return "redirect:/user/update.html?uid="+user.getId();
    }


    @RequestMapping(value="/user/add.html",method=RequestMethod.GET)
    public String toAddUser(User user,Model mode) {
        return "/user/add";
    }

    @RequestMapping(value="/user/add.html",method=RequestMethod.POST)
    public String doAddUser(@Valid User user,BindingResult bindingResult) {
        System.out.println("doAddUser");
        if(bindingResult.hasErrors()) {
            return "/user/add";
        }

        boolean val=userService.addUser(user);
        if(val) {
            // 成功：转跳用户列表页面
            return "redirect:/user/list.html";
        }
        // 失败：返回添加用户页面
        return "redirect:/user/add.html";
    }

    @RequestMapping(value="/user/list.html")
    public String toUserList(Model model,
                             @RequestParam(value="queryUserCode",required=false) String queryUserCode,
                             @RequestParam(value="queryUserName",required=false) String queryUserName,
                             @RequestParam(value="queryUserRole",required=false) Integer queryUserRole,
                             @RequestParam(value="queryUserStatus",required=false) Boolean queryUserStatus,
                             @RequestParam(value="pageIndex",defaultValue="1") Integer pageIndex
    ) {
        // 从数据库加载数据

        // 获取用户记录数
        int totalCount = userService.findUserCount(queryUserCode, queryUserName, queryUserRole, queryUserStatus);

        // 分页控制：获取总页码
        PageSupport pSupport=new PageSupport();
        pSupport.setCurrentPageNo(pageIndex);// 当前页码
        pSupport.setPageSize(Constants.pageSize);// 页面容量
        pSupport.setTotalCount(totalCount);// 总记录数
        int totalPageCount=pSupport.getTotalPageCount();// 总页数
        if(pageIndex>totalPageCount) {
            pageIndex=totalPageCount;
        }else if(pageIndex<1) {
            pageIndex=1;
        }

        // 获取用户列表
        List<User> userList=userService.findUserList(queryUserCode, queryUserName, queryUserRole, queryUserStatus,
                pageIndex, Constants.pageSize);

        // 回传数据：查询条件、分页参数、用户列表
        model.addAttribute("userList", userList);

        model.addAttribute("queryUserCode", queryUserCode);
        model.addAttribute("queryUserName", queryUserName);
        model.addAttribute("queryUserRole", queryUserRole);
        model.addAttribute("queryUserStatus", queryUserStatus);

        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("totalCount", totalCount);

        return "user/list";
    }

    @RequestMapping("/user/delete.html")
    @ResponseBody
    public String delete(Integer uid){

        HashMap<String,String> map = new HashMap<String, String>();

        User user = userService.getUserByUid(uid);
        if(user!=null){
            try {
                userService.deleteUserByUid(uid);
                System.out.println("您成功删除了"+user);
                map.put("delResult","true");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("您没能删除"+user);
                map.put("delResult","false");
            }
        }else {
            System.out.println("该用户不存在");
            map.put("deResulte","notexist");
        }
        return JSON.toJSONString(map);
    }
}
